import axios, { AxiosRequestConfig } from 'axios';
import { UserModule, ITokenType } from '../store/modules/user';


const AuthorizationHead: string = 'Bearer';

export default (store: any, router: any) => {

    axios.defaults.validateStatus = function (status: number) {
        return (status >= 200 && status < 300) || status === 422;// default
    };
    axios.interceptors.request.use(function (config: AxiosRequestConfig): AxiosRequestConfig {
        let token = UserModule.token;
        let token_type = AuthorizationHead;
        if (!token) {
            return config;
        }
        if (token.token_type) {
            token_type =token.token_type;
        }
        if (token.access_token) {
            config.headers.common['Authorization'] = `${token_type} ${token.access_token}`;
        }
        config.headers.common['Access-Control-Allow-Methods'] = config.method;
        config.headers.common['Accept'] = 'application/json';
        config.withCredentials = true;
        return config;
    }, function (error): Promise<any> {
        return Promise.reject(error);
    });

    axios.interceptors.response.use(function (response: any) {
        let result = null;
        let token_old:ITokenType|undefined = UserModule.token;
        let toke_type: string|undefined = AuthorizationHead;
        let token = response && response.headers && response.headers.authorization ? response.headers.authorization : null;

        if (token_old) {
            toke_type = token_old.token_type;
        }
        if (token) {
            token = token.slice(AuthorizationHead.length + 1);
            UserModule.SAVE_TOKEN({
                'access_token': token,
                'token_type': toke_type
            })
        }
        if (response.status === 422) {
            let data: { [key: string]: any } = {};
            Object.keys(response.data.errors).forEach(key => {
                if (response.data.errors[key] instanceof Array) {
                    data[key] = response.data.errors[key][0];
                } else {
                    data[key] = response.data.errors[key];
                }
            });
            result = { success: false, error: data };
        } else {
            result = response.data;
        }

        return Promise.resolve(result);
    }, function (error): Promise<any> {
        if (error.response) {
            if (error.response.status === 401) {
                UserModule.REMOVE_USER();
                router.push('/login');
            }
        }
        return Promise.resolve({ success: false });
    });
    return axios;

}
